<template>
	<view class="container">

		<view class="">

			<view class="goods-list" v-if="goodsList.length > 0">
				<view class="goods-item" v-for="goods in goodsList" :key="goods.id">
					<view class="goods-image" @click="navigateToDetail(goods.id)">
						<image :src="goods.thumb" mode="aspectFill"></image>
					</view>
					<view class="goods-info" @click="navigateToDetail(goods.id)">
						<text class="goods-name">{{goods.goods_name}}</text>
						<text class="goods-description">{{goods.description}}</text>
						<text class="goods-price">{{goods.sell_price}}元/{{goods.company}}</text>
						<text class="goods-stock">库存: {{goods.num}}</text>
					</view>
					<button class="add-cart-btn" type="primary" size="mini" @click="showSpecModal(goods)">加入购物车</button>
				</view>
			</view>

			<view class="no-result" v-else>
				<text>暂无商品结果</text>
			</view>
		</view>
		<!-- 规格选择弹窗组件 -->
		<spec-modal v-if="currentGoods" :goods="currentGoods" :show.sync="specModalShow"
			@confirm="handleSpecConfirm"></spec-modal>
	</view>
</template>

<script>
	import specModal from '../../components/specModal.vue';
	import api from '../../api/request';

	// 定义页面类型常量
	const PAGE_TYPE = {
		SPIKE: 1, // 限时抢购
		RECOMMEND: 2, // 推荐商品
		PROMOTION: 3, // 促销商品
		OFTEN_USE: 4 // 常用商品
	};

	export default {
		components: {
			specModal
		},
		data() {
			return {
				searchWord: '', // 搜索关键词
				goodsList: [], // 搜索结果商品列表
				hotTags: ['花椒', '米', '泡菜', '厨房用品', '调味'], // 热门搜索标签
				currentGoods: null, // 当前选中的商品
				specModalShow: false, // 规格弹窗显示状态
				pageType: 0, // 页面类型，0表示普通搜索
				currentPage: 1, // 当前页码
				isLoading: false // 是否正在加载数据
			};
		},
		onLoad(options) {
			// 初始化页码
			this.currentPage = 1;

			// 检查是否有id参数
			if (options && options.id) {
				this.pageType = parseInt(options.id);
				this.loadGoodsByType();
			}
			// 如果从其他页面携带搜索关键词过来
			else if (options && options.keyword) {
				this.searchWord = options.keyword;
				this.searchGoods();
			}
		},

		// 监听页面滚动到底部
		onReachBottom() {
			// 防止重复加载
			if (this.isLoading) return;

			this.isLoading = true;
			this.currentPage++;

			if (this.pageType === 0) {
				// 普通搜索
				this.searchGoods();
			} else {
				// 分类加载
				this.loadGoodsByType();
			}
		},
		methods: {
			// 搜索商品
			searchGoods() {
				if (!this.searchWord.trim()) {
					return;
				}

				const params = {
					page: this.currentPage,
					search_word: this.searchWord
				};

				api.getGoodsList(params)
					.then(res => {
						if (res.data && res.data.rows) {
							this.goodsList = res.data.rows;
						} else {
							this.goodsList = [];
						}
					})
					.catch(err => {
						console.error('搜索商品失败:', err);
						this.goodsList = [];
					});
			},

			// 根据类型加载商品
			loadGoodsByType() {
				const params = {
					page: this.currentPage
				};

				switch (this.pageType) {
					case PAGE_TYPE.SPIKE:
						api.spikeGoods(params)
							.then(res => this.handleGoodsResponse(res))
							.catch(err => this.handleGoodsError(err));
						break;
					case PAGE_TYPE.RECOMMEND:
						api.getRecommendGoodsList(params)
							.then(res => this.handleGoodsResponse(res))
							.catch(err => this.handleGoodsError(err));
						break;
					case PAGE_TYPE.PROMOTION:
						api.promotionGoods(params)
							.then(res => this.handleGoodsResponse(res))
							.catch(err => this.handleGoodsError(err));
						break;
					case PAGE_TYPE.OFTEN_USE:
						api.oftenUse(params)
							.then(res => this.handleGoodsResponse(res))
							.catch(err => this.handleGoodsError(err));
						break;
					default:
						console.error('未知页面类型:', this.pageType);
						this.goodsList = [];
				}
			},

			// 处理商品列表响应
			handleGoodsResponse(res) {
				this.isLoading = false;
				if (res.data && res.data.rows) {
					// 如果是第一页，替换商品列表
					if (this.currentPage === 1) {
						this.goodsList = res.data.rows;
					} else {
						// 如果是分页加载，追加商品列表
						this.goodsList = [...this.goodsList, ...res.data.rows];
					}
				} else {
					// 如果没有数据且不是第一页，回退页码
					if (this.currentPage > 1) {
						this.currentPage--;
					}
					uni.showToast({
						title: '没有更多数据了',
						icon: 'none'
					});
				}
			},

			// 处理商品列表请求错误
			handleGoodsError(err) {
				this.isLoading = false;
				// 如果是分页加载失败，回退页码
				if (this.currentPage > 1) {
					this.currentPage--;
				}
				console.error('加载商品失败:', err);
				uni.showToast({
					title: '加载商品失败',
					icon: 'none'
				});
			},

			// 热门标签搜索
			searchByTag(tag) {
				this.searchWord = tag;
				this.searchGoods();
			},

			// 显示规格选择弹窗
			showSpecModal(goods) {
				this.currentGoods = goods;
				this.specModalShow = true;
			},

			// 跳转到商品详情页
			navigateToDetail(goodsId) {
				uni.navigateTo({
					url: `/pages/goods/detail?goods_id=${goodsId}`
				})
			},

			// 处理规格确认
			handleSpecConfirm(data) {
				const {
					goods_id,
					num,
					item
				} = data;

				api.addCart({
						goods_id,
						num,
						item
					})
					.then(res => {
						uni.showToast({
							title: '添加购物车成功',
							icon: 'success'
						});
					})
					.catch(err => {
						uni.showToast({
							title: err.msg || '添加购物车失败',
							icon: 'none'
						});
					});
			}
		}
	};
</script>

<style scoped>
	/* 商品列表样式 */
	.goods-list {
		display: flex;
		flex-direction: column;
		gap: 10px;
		padding: 10px 0;
	}

	.goods-item {
		display: flex;
		/* width: 100%; */
		margin-bottom: 10px;
		background-color: #fff;
		border-radius: 8px;
		overflow: hidden;
		position: relative;
		padding: 10px;
		box-shadow: 0 1px 5px rgba(0, 0, 0, 0.05);
	}

	.goods-image {
		width: 120px;
		height: 120px;
		margin-right: 10px;
		flex-shrink: 0;
	}

	.goods-image image {
		width: 100%;
		height: 100%;
	}

	.goods-info {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}

	.goods-name {
		font-size: 14px;
		color: #333;
		margin-bottom: 5px;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 1;
		overflow: hidden;
	}

	.goods-description {
		font-size: 24rpx;
		color: #666;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 1;
		overflow: hidden;
	}

	.goods-price {
		font-size: 16px;
		color: #e63946;
		font-weight: bold;
	}

	.goods-stock {
		font-size: 12px;
		color: #999;
	}

	.add-cart-btn {
		position: absolute;
		bottom: 20rpx;
		right: 20rpx;
		background-color: #FE0000;
		color: #fff;
		font-size: 24rpx;
		padding: 0 20rpx;
		height: 50rpx;
		line-height: 50rpx;
		border-radius: 25rpx;
		z-index: 10;
	}

	/* 无结果样式 */
	.no-result {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 200px;
		color: #999;
	}
</style>